package datastructure.stak;


import java.util.Iterator;

/**
 * 数组实现栈
 *
 * @author 杨 强
 * @package datastructure.stak
 * @createTime 2023-03-14 21:49
 */
public class ArrayStack<E> implements Stack<E>, Iterable<E> {
    public static void main(String[] args) {
        ArrayStack<Integer> stack = new ArrayStack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);

        Iterator<Integer> iterator = stack.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        System.out.println("弹出了" + stack.pop());

        Iterator<Integer> iterator1 = stack.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
    }

    /**
     * 存放元素的数组
     */
    private E[] array;
    /**
     * 指针,初始化在数组0下标
     */
    private int top=0;

    /**
     * 构造器,初始化数组容量
     * @param capacity 容量
     */
    public ArrayStack(int capacity) {
        array = (E[]) new Object[capacity];
    }

    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }
        // top位置存放值
        array[top] = value;
        // 指针加一, 合成一句 array[top++] = value;  也可以
        top++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        // 可以合成一句  return array[--top];
        E e = array[top - 1];
        top--;
        return e;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[top-1];
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == array.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = top;
            @Override
            public boolean hasNext() {
                return p > 0;
            }

            @Override
            public E next() {
                return array[--p];
            }
        };
    }
}
